package gitee

import (
	"encoding/json"
	"fmt"

	"gitee.com/StarCitizen_CN/logger"
	"gitee.com/StarCitizen_CN/stargox/pkg/codes"
)

func GetLastReleaseWithGitee(repoAddress, mirror string) (release *Release, err error) {

	if mirror == "" {
		mirror = "gitee.com"
	}

	repoOwner, repoName := parseGiteeHttpUrlRepo(repoAddress)
	releaseUrl := fmt.Sprintf("https://%s/api/v5/repos/%s/%s/releases/latest", mirror, repoOwner, repoName)
	data, err := Get(releaseUrl)
	if err != nil {
		return nil, err
	}
	release = &Release{}
	jsonErr := json.Unmarshal(data, release)
	if jsonErr != nil {
		err = fmt.Errorf(codes.ErrParsingTagsJson, jsonErr)
		return nil, err
	}

	return release, nil
}

// 用于检查更新
func GetLastReleaseTagWithGitee(repoAddress string) (lastTag string, err error) {

	defer func(err *error) {
		if err != nil {
			logger.Err(*err)
		}
	}(&err)

	var tags []GiteeTag
	repoOwner, repoName := parseGiteeHttpUrlRepo(repoAddress)

	tagsUrl := fmt.Sprintf("https://gitee.com/api/v5/repos/%s/%s/tags", repoOwner, repoName)
	data, err := Get(tagsUrl)
	if err != nil {
		return
	}
	jsonErr := json.Unmarshal(data, &tags)
	if jsonErr != nil {
		err = fmt.Errorf(codes.ErrParsingTagsJson, jsonErr)
		return
	}

	var lastTagVar GiteeTag
	for _, t := range tags {
		lastTagDate, _ := parseGiteeTime(lastTagVar.Commit.Date)
		tagDate, _ := parseGiteeTime(t.Commit.Date)

		if lastTagDate.Before(tagDate) {
			lastTagVar = t
		}
	}

	lastTag = lastTagVar.Name
	return
}
